import 'package:flutter/cupertino.dart';

/// @author 高裕
/// 实时检测高度的widget
class KqSizeReportingWidget extends StatefulWidget {
  final Widget child;
  final ValueChanged<Size?> onSizeChange;

  /// 检测出和上次返回数据相同的数据时，是否返回数据,true是返回
  final bool? isReturnSameSize;

  const KqSizeReportingWidget({
    super.key,
    required this.child,
    required this.onSizeChange,
    this.isReturnSameSize,
  });

  @override
  State<KqSizeReportingWidget> createState() => _KqSizeReportingWidgetState();
}

class _KqSizeReportingWidgetState extends State<KqSizeReportingWidget> {
  Size? _oldSize;

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((_) => _notifySize());
    return widget.child;
  }

  void _notifySize() {
    if (!mounted) {
      return;
    }
    final size = context.size;
    if (widget.isReturnSameSize ?? false) {
      widget.onSizeChange(size);
    } else {
      if (_oldSize != size) {
        _oldSize = size;
        widget.onSizeChange(size);
      }
    }
  }
}
